package com.lagou.edu.mvcframework.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * <p>
 *  安全拦截器
 * </p>
 *
 * @author KK
 * @since 2021-08-29
 */
public class SecurityHandlerInterceptor implements HandlerInterceptor {

    private List<String> authorized;


    public SecurityHandlerInterceptor(List<String> authorized) {
        this.authorized = authorized;
    }

    /**
     * 当传入的username没有权限时, preHandle方法则返回false, 并且向response写入错误提示信息;
     * @param request 请求
     * @param response 响应
     * @param handler handler方法
     * @return 当传入的username没有权限时, preHandle方法则返回false, 并且向response写入错误提示信息;
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        // 获取用户名
        String username = request.getParameter("username");


        // 判断是否有权限
        if (authorized.contains(username)){
            return true;
        }else{
            // 如果没有权限， 向response写入错误信息
            response.getWriter().write("401 Unauthorized");
            response.flushBuffer();

            return false;
        }

    }
}
